<template>
  <div class="greenhouse-info">
    <!-- 数据展示表格 -->
    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th>设备名称</th>
            <th>单位</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>{{ item.nameAndCategory }}</td>
            <td>{{ item.unit || "无单位" }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="2">已绑定设备总数: {{ tableData.length }}</td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import axios from "axios";

// 表格数据
const tableData = ref([]);

// 请求数据并更新表格内容
const fetchSensorData = async () => {
  try {
    const loginResponse = await axios.post("http://localhost:8080/api/login", {
      username: "root",
      password: "123"
    });
    const token = loginResponse.data.data.token;
    const response = await axios.get("http://localhost:8080/api/sensor/data", {
      headers: {
        Authorization: `Bearer ` + token
      }
    });
    tableData.value = response.data;
  } catch (error) {
    console.error("获取传感器数据失败", error);
  }
};

// 挂载时加载数据
onMounted(fetchSensorData);
</script>

<style lang="scss" scoped>
.greenhouse-info {
  padding: 20px;
  color: #ffffff;
  background: #0c0a4a;
  border-radius: 8px;
  .table-container {
    margin-top: 20px;
    overflow-x: auto;
    table {
      width: 100%;
      overflow: hidden;
      color: #ffffff;
      border-collapse: collapse;
      background-color: #222222;
      border-radius: 8px;
      thead {
        background-color: #333333;
        tr {
          th {
            padding: 10px;
            font-weight: bold;
            text-align: left;
            border-bottom: 1px solid #444444;
          }
        }
      }
      tbody {
        tr {
          &:hover {
            background-color: #444444;
          }
          td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #444444;
          }
        }
      }
      tfoot {
        tr {
          td {
            padding: 10px;
            font-weight: bold;
            text-align: left;
            background-color: #333333;
          }
        }
      }
    }
  }
}
</style>
